﻿/* SharePoint Console Project
 * Http://SharePointConsole.codeplex.com
 * Copyright Jean-Alain Baeyens (2009)
 * Software under Microsoft Reciprocal License (Ms-RL)
 */

using System;

using Microsoft.SharePoint.WebPartPages;
using System.Web.UI.WebControls.WebParts;
using Sharepoint.Console.Commands;

namespace Sharepoint.Console.WebParts
{
    class ActiveWebPartsConnection : RecursiveBaseCommande
    {
        public override string ShortHelp
        {
            get
            {
                return "Active connection between two web parts";
            }
        }

        public override string LongHelp
        {
            get
            {
                return "Active the predefined  the connection between two web part.The connection must be defined into the xml definition file of the web parts.";
            }
        }

        public override string Syntax
        {
            get
            {
                return "ConnectWebPart 'PageUrl' 'ConsumerWebParTitel' 'ProviderWebPartTitel'";
            }
        }

        public override string Execute(string[] args)
        {
            if (args.Length != 4) return string.Format("Invalide syntax. Use {0}", Syntax);

            string page = args[1];
            string titleWP1 = args[2];
            string titleWP2 = args[3];

            SPLimitedWebPartManager wpm = null;
            System.Web.UI.WebControls.WebParts.WebPart wp1 = null;
            System.Web.UI.WebControls.WebParts.WebPart wp2 = null;

            try
            {
                wpm = this.SharepointConnection.Web.GetLimitedWebPartManager(page, PersonalizationScope.Shared);
                SharepointHelper helper = new SharepointHelper();
                wp1 = helper.GetWebPart(wpm, titleWP1);
                wp2 = helper.GetWebPart(wpm, titleWP2);
                if (wp1 != null && wp2 != null)
                {
                    ProviderConnectionPointCollection provider = wpm.GetProviderConnectionPoints(wp1);
                    ConsumerConnectionPointCollection consumer = wpm.GetConsumerConnectionPoints(wp2);
                    SPWebPartConnection wpConn = wpm.SPConnectWebParts(wp1,provider[0],wp2,consumer[0]); 
                    return "Webparts connected";
                }
                else
                {
                    if (wp1 == null)
                    {
                        return string.Format("Webpart {0} not found", titleWP1);
                    }
                    else
                    {
                        return string.Format("Webpart {0} not found", titleWP2);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
